package com.shibaobei.activity.service;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * 流程定义
 * Created by Administrator on 2020/4/29 0029.
 */
@Service
public class ProcessDefinitionService {
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 查询最新版本的流程定义列表
     * @return
     */
    public List<ProcessDefinition> findLastList(){
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        processDefinitionQuery.orderByProcessDefinitionVersion().asc();
        List<ProcessDefinition> list = processDefinitionQuery.list();
        Map<String,ProcessDefinition> map = new HashMap<>();
        list.forEach(pd->{
            map.put(pd.getKey(),pd);
        });
        return new ArrayList<ProcessDefinition>(map.values());
    }


    public void deleteByKey(String key) {
        //根据key查询流程定义
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
        query.processDefinitionKey(key);
        List<ProcessDefinition> list = query.list();
        list.forEach(pd->{
            repositoryService.deleteDeployment(pd.getDeploymentId(),true);
        });

    }

    /**
     * 部署流程定义
     * @param resource
     */
    public void deploy(MultipartFile resource) {
        DeploymentBuilder deployment = repositoryService.createDeployment();
        try {
            String fileName = resource.getOriginalFilename();
            String filePath = "E:\\IntellijIDEATechnology\\sbb-activity";
            File dest = new File(filePath + fileName);
            resource.transferTo(dest);

            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(dest));
            deployment.addZipInputStream(zipInputStream);
            deployment.deploy();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public InputStream showPng(String processDefinitionId) {
        return repositoryService.getProcessDiagram(processDefinitionId);
    }
}
